<template>
	<div class="video-test">
		<div class="pointMark_video">
			<div id="newTestDom">
				<!-- <video id="videoTestPlayer" ref="videoTestPlayer" class="video-js vjs-big-play-centered" width="100%" height="100%"
				 oncontextmenu="return false;" disablePictureInPicture controlslist="nodownload">
				</video> -->
				<dplayer key="dplayer" ref="dplayer" :playParam.sync="playerOptions" :pointData="this.allTestData">
				</dplayer>
			</div>
		</div>

		<div class="publishFrom">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
				<el-form-item label="测试名称" prop="text">
					<el-input v-model.trim="ruleForm.test_name" placeholder="最多可以输入20个字"></el-input>
				</el-form-item>
				<div class="publishFrom_if clear">
					<el-form-item label="打点时间" prop="test_time" class="publishFrom_if_l fl">
						<span>
							<el-time-picker v-model="ruleForm.test_time" value-format="HH:mm:ss" :picker-options="{
								format: 'HH:mm:ss',
								selectableRange: timeMax
							}" placeholder="任意时间点">
							</el-time-picker>
						</span>
						<i class="el-icon-location" @click="getVideoPlayTime"></i>
					</el-form-item>
					<div class="publishFrom_if_r fr">
						<el-form-item class="buttonCSS" label-width="0">
							<el-button type="primary" @click="showTestDialog(true)">添加测试</el-button>
						</el-form-item>
					</div>
				</div>
			</el-form>
		</div>

		<div class="publishFrom_table">
			<template>
				<el-table border :data="allTestData" style="width: 100%">
					<el-table-column prop="test_name" label="测试名称" align="center">
					</el-table-column>
					<el-table-column prop="question_count" label="试题数量" align="center">
					</el-table-column>
					<el-table-column prop="test_time" label="测试时间" align="center">
					</el-table-column>
					<el-table-column prop="test_record_user_count" label="测试人次" align="center">
					</el-table-column>
					<el-table-column label="操作" align="center" width="120">
						<template slot-scope="scope">
							<el-button @click="showTestDialog(false, scope.row)" type="text" size="small">编辑</el-button>
							<el-button @click="deleteTest(scope.row)" class="delete-button" type="text" size="small">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</template>
		</div>

		<el-dialog :title="isAdd ? '新增测试' : '编辑测试'" :visible.sync="testVisible" width="880px" @close="handleClose"
			:close-on-click-modal="false">
			<div class="questionView">
				<el-tabs v-model="tabTempIndex" type="card" editable @edit="handleTabsEdit" class="addAlbum_msg">
					<el-tab-pane v-for="(item, index) in ruleForm.test_data" :label="item.title" :name="item.name"
						:key="item.name">
						<div class="questionView_c">
							<el-form label-width="80px">
								<el-form-item label="题干">
									<el-input v-model.trim="item.problem" type="textarea" resize="none" :rows="4"
										placeholder="点击编辑单选题干，并选择正确答案"></el-input>
								</el-form-item>
								<el-form-item label="A">
									<el-input v-model.trim="item.A" placeholder="点击编辑选项"></el-input>
								</el-form-item>
								<el-form-item label="B">
									<el-input v-model.trim="item.B" placeholder="点击编辑选项"></el-input>
								</el-form-item>
								<el-form-item label="C">
									<el-input v-model.trim="item.C" placeholder="点击编辑选项"></el-input>
								</el-form-item>
								<el-form-item label="D">
									<el-input v-model.trim="item.D" placeholder="点击编辑选项"></el-input>
								</el-form-item>
								<el-form-item label="正确答案">
									<el-radio-group v-model="item.answer">
										<el-radio label="A"></el-radio>
										<el-radio label="B"></el-radio>
										<el-radio label="C"></el-radio>
										<el-radio label="D"></el-radio>
									</el-radio-group>
								</el-form-item>
								<el-form-item label="解析" class="tinymce-resolve">
									<tinymce :id="`d1${index}`" :plugins="plugins" :ref="`tinymce${index}`" :other_options="options"
										:toolbar1="toolbar1" :toolbar2="toolbar2" :images_upload_handler="images_upload_handler"
										v-model="item.resolve" @editorInit="editorInit($event, item.resolve, index)">
									</tinymce>
								</el-form-item>
							</el-form>
						</div>
					</el-tab-pane>
				</el-tabs>
				<div class="btnCss">
					<el-button v-if="isAdd" type="primary" @click="addNewTest()">生成测试点</el-button>
					<el-button v-else style="width: 120px;" type="primary" @click="editTest()">保存</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>
<script>
import tinymce from 'vue-tinymce-editor';
import axios from './../../../../tools/axios';
import dplayer from '@/components/public/dplayer.vue';

export default {
	components: {
		tinymce,
		dplayer,
	},
	props: ['compParam', 'activeIndex'],
	data() {
		return {
			isreturn: false,
			// 播放器：
			player: null,
			// playerOptions: {
			// 	loop: false, // true -- 视频一结束就重新开始
			// 	controls: true,
			// 	fluid: false,
			// 	autoplay: false, // true--浏览器准备好时开始回放
			// 	height: '360',
			// 	poster: "", // 封面地址
			// 	language: 'zh-CN',
			// 	sources: [{
			// 		type: "application/x-mpegURL",
			// 		src: this.compParam.play_url // 视频播放路径
			// 	}],
			// 	controlBar: {
			// 		children: [{
			// 			name: 'playToggle'
			// 		}, // 播放按钮
			// 		{
			// 			name: 'currentTimeDisplay'
			// 		}, // 当前已播放时间
			// 		{
			// 			name: 'progressControl'
			// 		}, // 播放进度条
			// 		{
			// 			name: 'durationDisplay'
			// 		}, // 总时间
			// 		{
			// 			name: 'volumePanel', // 音量控制
			// 			inline: false, // 不使用水平方式
			// 		},
			// 		{
			// 			name: 'FullscreenToggle'
			// 		} // 全屏
			// 		]
			// 	},
			// },

			// 测试数据相关：
			playerOptions: {
				play_url: this.compParam.play_url,
			},
			ruleForm: {
				id: 0,//当前视频id
				test_id: '',
				test_name: '', //测试名称
				test_time: '00:00:00',//打点时间
				test_data: [{
					title: '第1题',
					name: '1',
					problem: '',
					A: '',
					B: '',
					C: '',
					D: '',
					answer: '',
					resolve: '',
				}],
			},
			rules: {
				test_name: [{ required: true, message: '请输入测试名称', trigger: 'blur' },
				{ min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
				],
				test_time: [{ required: true, message: '请输入打点时间', trigger: 'blur' }
				]
			},
			allTestData: [],
			testVisible: false,
			isAdd: true,

			tabTempIndex: '1',

			// 富文本相关设置：
			plugins: ['paste', 'fullscreen', 'link', 'image'],
			toolbar1: 'paste,fullscreen,link',
			toolbar2: 'table |insertfile undo redo | formatselect  | fontsizeselect | forecolor backcolor | fontselect bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | link | image | removeformat',
			options: {
				images_upload_handler: this.images_upload_handler,
				language_url: '/static/tinymce_languages/zh_CN.js',
				images_upload_url: this.BASE_URL + '/api/resource/res_upload_permanent',
				paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
				paste_convert_word_fake_lists: false, // 插入word文档需要该属性
				paste_webkit_styles: 'all',
				paste_merge_formats: true,
				nonbreaking_force_tab: false,
				paste_auto_cleanup_on_paste: false,
				convert_urls: false,
				font_formats: `
                        微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;
                        宋体='宋体',Helvetica,Arial,sans-serif;
                        仿宋='仿宋',Helvetica,Arial,sans-serif;
                        楷体='楷体',Helvetica,Arial,sans-serif;
                        黑体='黑体',Helvetica,Arial,sans-serif;
                        幼圆='幼圆',Helvetica,Arial,sans-serif;
                        隶书='隶书',Helvetica,Arial,sans-serif;
                        华文新魏='华文新魏',Helvetica,Arial,sans-serif;
                        苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;
                        Arial='Arial',Helvetica,Arial,sans-serif;
                        Verdana=verdana,geneva;
                        Webdings=webdings
                    `,
			},
		}
	},
	mounted() {
		// this.initPlay();
		this.getTestData();
	},
	computed: {
		timeMax() {
			return this.compParam.length ? ('00:00:00 - ' + this.compParam.length) : '00:00:00 - 00:00:00';
		}
	},
	beforeDestroy() {
		this.player && this.player.dispose();
	},
	methods: {
		//播放器初始化
		initPlay() {
			let self = this;
			this.player && this.player.dispose();
			let videoTestPlayer = document.getElementById('newTestDom');
			videoTestPlayer.innerHTML =
				'<video id="videoTestPlayer" class="video-js vjs-big-play-centered" width="100%" height="100%" oncontextmenu="return false;" disablePictureInPicture controlslist="nodownload"> </video>'
			this.player = this.$videojs('videoTestPlayer', this.playerOptions, function onPlayerReady() { })

			// 初始音量50%
			this.player.volume(0.5)

			// 播放器准备就绪
			this.player.on('loadedmetadata', function () {
				self.getTestData();
			});
		},
		// 获取测试表格的数据
		getTestData() {
			let success = (data => {
				// console.log(data)
				this.allTestData = data.data;
				for (var i = this.allTestData.length - 1; i >= 0; i--) {
					var newTime = formatSeconds(this.allTestData[i].test_time);
					this.allTestData[i].test_time_num = this.allTestData[i].test_time;
					this.allTestData[i].test_time = newTime.hour + ':' + newTime.minute + ':' + newTime.second
					this.allTestData[i].time = parseInt(newTime.second) + parseInt(newTime.minute) * 60 + parseInt(newTime.hour) * 3600
					// this.allTestData[i] = JSON.parse(JSON.stringify(this.allTestData[i]).replace(/test_name/g, 'text'));
					this.allTestData[i].text = this.allTestData[i].test_name;
				}
				// console.log('aaa',this.allTestData)
				// this.resolveMark();
			})
			let fail = (data => {
				this.$message.error(data.msg)
			})
			this.$ajax.get('api/video/video_test', {
				params: {
					id: this.compParam.id
				},
				func: {
					success: success,
					fail: fail
				}
			})
		},
		// 测试题目的table删除事件
		deleteTest(obj) {
			let yes = (data => {
				let success = (data => {
					this.$message.success(data.msg)
					this.getTestData();
				})
				this.$ajax.delete('api/video/video_test', {
					params: {
						id: obj.id
					},
					func: {
						success: success
					}
				})
			})
			let cancel = (data => { })
			this.e_confirm({
				yes: yes,
				cancel: cancel,
				txt: '确定将 ' + obj.test_name + ' 删除吗？'
			});
		},

		// 视频打点
		// resolveMark() {
		// 	//先删除所有打点
		// 	var dotting_time_element = this.player.controlBar.progressControl.el_.children[0].getElementsByClassName(
		// 		'dotting_time');
		// 	if (dotting_time_element.length > 0) {
		// 		for (var i = dotting_time_element.length - 1; i >= 0; i--) {
		// 			this.player.controlBar.progressControl.el_.children[0].removeChild(dotting_time_element[i]);
		// 		}

		// 	}
		// 	if (this.allTestData.length > 0) {
		// 		var newTime = this.compParam.length.split(':');
		// 		var total_time_num = parseInt(newTime[0]) * 3600 + parseInt(newTime[1]) * 60 + parseInt(newTime[2]);
		// 		for (var i = 0; i < this.allTestData.length; i++) {
		// 			var left = this.allTestData[i].test_time_num / total_time_num * 100;
		// 			var html =
		// 				`<div class="dotting_time"  
		// 								style="background:#54b554;
		// 								left: ${left}%;
		// 								width:5px;height:100%;
		// 								position:absolute;z-Index:55;"
		// 								 current_time="">
		// 								<div class="low_source">
		// 									<p class="low_h">${this.allTestData[i].test_name}</p>

		// 								</div>
		// 							</div>`
		// 			this.player.controlBar.progressControl.el_.children[0].insertAdjacentHTML('beforeend', html)
		// 		}
		// 	}
		// },
		// 获取视频当前播放进度时间
		getVideoPlayTime() {
			// var nowTime = formatSeconds(this.player.currentTime());
			// this.ruleForm.test_time = nowTime.hour + ':' + nowTime.minute + ':' + nowTime.second
			this.$refs.dplayer.player.pause();
			let nowTime = formatSeconds(this.$refs.dplayer._data.videoCurrentTime)

			// console.log(nowTime)
			this.ruleForm.test_time = nowTime.hour + ':' + nowTime.minute + ':' + nowTime.second
		},

		//显示测试弹窗 flag:true新增测试,false编辑测试;test：编辑的单个测试数据
		showTestDialog(flag, test) {
			this.isAdd = flag;
			if (flag) {
				this.$refs.ruleForm.validate((valid) => {
					if (valid) {
						this.testVisible = true;
					} else {
						return false;
					}
				});
			} else {
				this.ruleForm.test_id = test.id;
				this.ruleForm.id = test.id;
				this.ruleForm.test_name = test.test_name;
				this.ruleForm.test_time = test.test_time;
				this.getSingleTest(test.id);
				this.testVisible = true;
			}
		},
		//编辑点击事件 - 获取单个测试的数据
		getSingleTest(testId) {
			let success = res => {
				const answerTitles = ['A', 'B', 'C', 'D'];
				this.ruleForm.test_data = []
				res.data.forEach((item, index) => {
					const inx = index + 1 + '';
					this.ruleForm.test_data.push({
						title: `第${inx}题`,
						name: inx,
						problem: item.problem,
						A: item.A,
						B: item.B,
						C: item.C,
						D: item.D,
						answer: answerTitles[item.answer - 1],
						resolve: item.resolve,
						question_id: item.question_id
					})
				})
				this.tabTempIndex = '1';
			}
			this.$ajax.get('api/video/test_question', {
				params: {
					id: testId
				},
				func: {
					success
				}
			})
		},
		// tabs新增/删除测试题目
		handleTabsEdit(targetName, action) {
			if (action === 'add') {
				this.tabTempIndex = this.ruleForm.test_data.length + 1 + '';
				this.ruleForm.test_data.push({
					title: `第${this.tabTempIndex}题`,
					name: this.tabTempIndex,
					problem: '',
					A: '',
					B: '',
					C: '',
					D: '',
					answer: '',
					resolve: '',
				});
			} else if (action === 'remove') {
				const tabs = deep_clone(this.ruleForm.test_data);
				if (tabs.length === 1) {
					this.$message.warning('只剩一个测试题了，不能再删除了');
					return;
				}
				// 删除项，重新设置tabs每一项的标题和索引
				this.ruleForm.test_data = tabs.filter(x => { return x.name != targetName }).map((y, inx) => {
					y.title = `第${inx + 1}题`;
					y.name = inx + 1 + '';
					return y;
				})
				// 重置tabs高亮选中
				let a = this.tabTempIndex;
				let b = targetName < a || (targetName == a && targetName != '1') ? a - 1 : a;
				this.tabTempIndex = b.toString();
			}
		},
		addNewTest() {
			this.ruleForm.test_data.forEach(item => {
				if (item.problem.length < 1) {
					this.$message.warning('题干不能为空');
					this.isreturn = true
				} else if (item.A.length < 1) {
					this.$message.warning('选项内容不能为空');
					this.isreturn = true
				} else if (item.B.length < 1) {
					this.$message.warning('选项内容不能为空');
					this.isreturn = true
				} else if (item.answer.length < 1) {
					this.$message.warning('正确答案不能为空');
					this.isreturn = true
				} else if (item.resolve.length < 1) {
					this.$message.warning('解析不能为空');
					this.isreturn = true
				}
			})
			if (this.isreturn) {
				this.isreturn = false
				return
			}

			// const hasEmptyInx = this.ruleForm.test_data.map(x => { 
			// 	if(Object.values(x).includes('')){
			// 		return x.name;
			// 	}
			// })
			// console.log(hasEmptyInx)
			// if(hasEmptyInx.length > 0){
			// 	this.$message.warning(`第${hasEmptyInx.toString()}题还未填写完整`);
			// 	return;
			// }
			let success = (data => {
				this.$message.success(data.msg)
				// console.log(this.$refs.dplayer.player.play)
				this.$refs.dplayer.player.play();
				this.resetForm('ruleForm');
				this.getTestData();
				this.ruleForm = {
					id: 0,
					test_name: '', //视频名称
					test_time: '00:00:00',
					test_data: [{
						title: '第1题',
						name: '1',
						problem: '',
						A: '',
						B: '',
						C: '',
						D: '',
						answer: '',
						resolve: '',
					}],
				}
				this.testVisible = false;
			})
			this.ruleForm.id = this.compParam.id;
			this.$ajax.post('api/video/video_test', this.ruleForm, {
				func: {
					success: success
				}
			})
		},
		editTest() {
			const success = res => {
				this.$message.success(res.msg)
				this.player.play();
				this.resetForm('ruleForm');
				this.getTestData();
				this.ruleForm = {
					id: 0,
					test_name: '', //视频名称
					test_time: '00:00:00',
					test_data: [{
						title: '第1题',
						name: '1',
						problem: '',
						A: '',
						B: '',
						C: '',
						D: '',
						answer: '',
						resolve: '',
					}],
				}
				this.testVisible = false;
			}
			const fail = res => {
				this.$message.error(res.msg)
			}
			this.$ajax.put('api/video/video_test', this.ruleForm, {
				func: {
					success,
					fail
				}
			})
		},
		handleClose() {
			this.tabTempIndex = '1';
			this.ruleForm = {
				id: 0,
				test_name: '', //视频名称
				test_time: '00:00:00',
				test_data: [{
					title: '第1题',
					name: '1',
					problem: '',
					A: '',
					B: '',
					C: '',
					D: '',
					answer: '',
					resolve: '',
				}],
			}
		},
		resetForm(formName) {
			this.$refs[formName].resetFields();
			this.ruleForm.test_time = '00:00:00';
			this.ruleForm.test_name = '';
		},

		/**
		 * 编辑器初始化
		 */
		editorInit(e, val, inx) {
			this.$refs[`tinymce${inx}`][0].editor.setContent(val);//编辑器bug，有时候会丢失，content值，此处重新设置content
			// 修改输入框内文字与边界的宽
			let dom = document.getElementById(`${e.id}_ifr`).contentWindow.document.getElementById('tinymce');
			dom.style.margin = "8px 25px 45px";
		},
		/**
		 * 图片上传三个参数，图片数据，成功时的回调函数，失败时的回调函数
		 */
		images_upload_handler(blobInfo, success, failure) {
			if (blobInfo.blob().type.indexOf('image/') === -1) {
				failure('只允许上传图片格式的文件')
			} else if (blobInfo.blob().size > 10240000) {
				failure('图片大小不能超过10M')
			} else {
				let formData = new FormData();
				formData.append('file', blobInfo.blob(), blobInfo.filename());
				let succ = (data => {
					// data.data =  data.data.data;
					success(this.BASE_URL + data.data.data.file_path)
				});
				let fail = (data => {
					// data.data =  data.data.data;
					failure(data.data.data.message)
				});
				//******************************TODO 不知为何要重新create*****************//
				const instance = axios.create({
					headers: {
						Authorization: `Bearer ${this.$g.access_token}`,
						DecisionPlatform: ` ${this.$g.access_token}`,
						token: sessionStorage.getItem('token'),
					},
					withCredentials: true,
				})
				instance.post('api/resource/res_upload_permanent', formData).then(succ).catch(fail)
			}
		},
	}
}
</script>

<style lang="scss">
.video-test {
	.mce-statusbar.mce-container.mce-panel.mce-stack-layout-item.mce-last {
		display: none;
	}

	#newTestDom {
		height: 400px;
	}

	.el-icon-location {
		font-size: 20px;
		color: #348efc;
		padding: 10px;
		background: #E8F2FF;
		border-radius: 3px;
		vertical-align: middle;
		cursor: pointer;
	}

	.mce-edit-area.mce-container.mce-panel.mce-stack-layout-item>iframe {
		height: 200px !important;
	}

	.mce-tinymce.mce-container.mce-panel[role=application]>div>div:first-child>div>div:first-child {
		display: none;
	}

	.mce-tinymce.mce-container.mce-panel[role=application]>div>div:first-child>div>div:last-child>div>div:first-child {
		display: none;
	}

	.tinymce-resolve {
		.el-form-item__content {
			margin-right: 3px;
		}
	}

	.questionView {
		.btnCss {
			text-align: center;
			padding: 20px 0 30px;
		}

		.el-tabs__item {
			font-size: 12px;
		}

		.el-tabs--card>.el-tabs__header .el-tabs__nav {
			border: 0;
			border-radius: 4px;
			background: #ecf5ff;

		}

		.el-tabs__new-tab {
			background: #338efc;
			border-color: #338efc;

			>i {
				color: #fff;
			}
		}

		.el-tabs__header {
			margin: 0 0 40px;
		}
	}

	.publishFrom {
		margin-top: 30px;
	}
}

.dotting_time {
	&:hover {
		.low_source {
			opacity: 1;
			visibility: visible;
		}
	}
}

.low_source {
	position: absolute;
	background: #fff;
	width: 200px;
	bottom: 20px;
	left: -100px;
	padding: 15px;
	border-radius: 4px;
	transition: .5s;
	opacity: 0;
	visibility: hidden;

	>p {
		color: #000;
		font-size: 12px;
		text-align: left;
		margin: 0;
	}

	>img {
		width: 100%;
		margin: 10px;
	}

	&:after {
		content: '';
		width: 0;
		height: 0;
		border-width: 12px 9px 0;
		border-style: solid;
		border-color: #fff transparent transparent;
		position: absolute;
		bottom: -12px;
		left: 50%;
		margin-left: -6px;
	}
}
</style>
